// 生成随机验证码
export function generateCaptcha(length = 4) {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 绘制验证码到 Canvas
export function drawCaptcha(code, width = 100, height = 32) {
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext('2d');

  // 填充白色背景
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, width, height);

  // 绘制文字
  ctx.fillStyle = '#000';
  ctx.font = '24px Arial';
  ctx.textBaseline = 'middle';
  
  // 随机偏移每个字符
  for (let i = 0; i < code.length; i++) {
    const x = (width / code.length) * i + 10;
    const y = height / 2 + Math.random() * 8 - 4;
    const rotate = (Math.random() - 0.5) * 0.3;
    
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(rotate);
    ctx.fillStyle = `rgb(${Math.random() * 150}, ${Math.random() * 150}, ${Math.random() * 150})`;
    ctx.fillText(code[i], 0, 0);
    ctx.restore();
  }

  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.5)`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }

  return canvas.toDataURL('image/png');
}